package web.servlet.datasource.book;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Administrator
 * @Date 2020/5/26 16:20
 **/
public class BookDaoDB implements BookDao {
    /**
     * spring框架简化开发
     */
    JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    /**
     * 定义sql
     */
    String sql = "";

    @Override
    public int insert(Book book) {
        /**
         * 准备sql
         * 利用JdbcTemplate执行sql语句
         * 判读用户名是否重复*/
        Book b = selectByName(book.getName());
        if (b == null) {
            sql = "insert into book(name,press,author,price) values(?,?,?,?)";
            int i = template.update(sql, book.getName(), book.getPress(), book.getAuthor(), book.getPrice());
            return i;
        } else {
            return -1;
        }
    }

    @Override
    public Book selectByName(String name) {
        sql = "select* from book where name = ?";
        try {
            Book book = template.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), name);
            return book;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    @Override
    public List<Book> selectAll() {
        sql = "select * from book";
        try {
            List<Book> list = template.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
            return list;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    @Override
    public int update(int id, Book book) {
        sql = "update book set name=?,press=?,author=?,price=? where id=?";
        int i = template.update(sql, book.getName(), book.getPress(), book.getAuthor(), book.getPrice(),id);
        return i;
    }

    @Override
    public int delete(int id) {
        sql = "delete from book where id=?";
        int i = template.update(sql, id);
        return i;
    }
}
